<template>
  <el-dialog class="gl_dialog_TitleLine" title="批量增加人员" :visible.sync="isShow" :close-on-click-modal="false" width="800px" @close="onCloseDialog">
    <div v-loading="modalLoading">
      <div class="gl_mb_20 gl_clear">
        <div class="import_info gl_fl">
          <div v-if="tableData.length" class="gl_fl gl_mr_20">导入成功 {{ tableData.length }}</div>
          <div v-if="failTableData.length" class="gl_fl">
            导入失败 {{ failTableData.length }}
            <el-popover
              placement="right"
              trigger="hover"
            >
              <ul class="fail_athlete_list">
                <li v-for="(item, index) in failTableData" :key="index" class="fail_athlete_item gl_mb_5">
                  <span style="min-width:180px" class="fail_text">
                    <span>{{ item.name }}</span>
                    <span v-show="item.idCardNumber">({{ item.idCardNumber }})</span>
                  </span>
                  <span class="fail_text gl_mr_10">{{ item.errorMsg }}</span>
                </li>
              </ul>
              <i slot="reference" class="el-icon-warning" />
            </el-popover>
          </div>
        </div>
        <div class="gl_fr">
          <!-- 下载导入模板 -->
          <a
            class="mock_btn gl_fl"
            target="_blank"
            download="导入模板"
            @click="downloadTmp(baseUrl + excelPath, '导入模板')"
          >
            下载导入模板
          </a>
          <!-- 上传文件 -->
          <upload-file
            ref="disclaimerNoticeUpload"
            class="gl_ml_10 gl_fl"
            :action="baseUrl + upLoadAction"
            file-type="file"
            format-file=".xls,.xlsx"
            default-file-name="导入人员"
            @changeModalLoading="changeModalLoading"
            @uploadSuccess="uploadSuccess"
            @uploadFail="uploadFail"
          />
        </div>
      </div>

      <!-- 运动员表格 -->
      <el-table ref="athleteTable" v-loading="tableLoading" class="gl_mb_15" :data="tableData" size="mini" height="400px">
        <el-table-column prop="name" label="头像" width="60" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.imagePath">
              <img class="import_athlete_face" :src="baseUrl + scope.row.imagePath" alt="">
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="national" label="民族" width="120" />
        <el-table-column prop="idCardNumber" label="证件号码" width="180" />
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="clickEditAthlete(scope.row, scope.$index)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog class="gl_dialog_TitleLine" title="编辑" append-to-body :visible.sync="dialogVisibleForPersonal" :close-on-click-modal="false" width="1200px">
        <div v-loading="dialogVisibleForPersonalLoading" class="gl_px_10">
          <personal-info ref="refPersonalInfo" :user-data="athleteVO" :is-default-check="athleteVO.isApproved" />
          <div slot="footer" align="right">
            <el-button size="mini" @click="dialogVisibleForPersonal = false">{{ $t('button.cancel') }}</el-button>
            <el-button size="mini" type="primary" @click="submitPersonalInfo">{{ $t('button.submit') }}</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </el-dialog>
</template>

<script>
import { CopyData } from '@/lib';

import uploadFile from './uploadFile';
import personalInfo from '@/components/PersonalInfo';

import {
  SiSTKWEventsManagementCreateRegisterWithTagsInput
} from '@/lib/form/game/swaggerForm';

import {
  api_GET_EventsManagementRegisterId,
  api_PUT_EventsManagementRegisterId
} from '@/extend/api/gameswaggerApi/app';

export default {
  components: {
    uploadFile,
    personalInfo
  },
  props: {
    dict: {
      type: Object,
      default () {
        return {};
      }
    }
  },
  data () {
    return {
      modalLoading: false, // 模态框Loading
      isShow: false, // 是否显示模态框
      tableLoading: false, // 表格Loading
      tableData: [], // 导入成功的数据
      failTableData: [], // 导入失败的数据
      athleteInfo: {}, // 编辑运动员时获取到的运动员信息
      currentAthleteIndex: 0, // 点击编辑时选中的运动员索引
      athleteVO: new SiSTKWEventsManagementCreateRegisterWithTagsInput(),
      dialogVisibleForPersonal: false, // 是否显示编辑运动员信息模态框
      dialogVisibleForPersonalLoading: false, // 编辑运动员信息Loading
      baseUrl: WEB_CONFIG.VUE_APP_SWAGGER_GAME_BASE, // 基本路径地址
      upLoadAction: '/api/app/events-management/register/import', // 导入人员路径
      excelPath: `/Files/Import_Template.xlsx` // 下载模板路径
    };
  },
  methods: {
    open () {
      this.isShow = true;
    },
    close () {
      this.isShow = false;
    },
    onCloseDialog () {
      this.tableData = [];
      this.failTableData = [];
    },
    // 点击编辑运动员
    clickEditAthlete (row, index) {
      this.currentAthleteIndex = index;
      this.getAthleteInfo(row.id);
    },
    // 确定修改运动员信息
    submitPersonalInfo () {
      this.$refs.refPersonalInfo.getInsideUserData()
        .then(
          res => {
            this.updatePersonalInfo(res);
          }
        );
    },
    // 更新运动员信息
    updatePersonalInfo (res) {
      this.dialogVisibleForPersonalLoading = true;
      CopyData(res, this.athleteVO);
      this.athleteVO.isCurrentUser = false;
      this.athleteVO.joinCurrentDelegation = true;
      api_PUT_EventsManagementRegisterId(this.athleteInfo.id, this.athleteVO)
        .then(
          (res) => {
            console.log('res: ', res);
            this.dialogVisibleForPersonalLoading = false;
            this.dialogVisibleForPersonal = false;
            this.$message({ type: 'success', message: '操作成功' });
            this.updateTableAthlete(res);
          },
          error => {
            this.dialogVisibleForPersonalLoading = false;
            this.$message({ type: 'error', message: `修改用户信息失败 ${error.error.message}` });
          }
        );
    },
    // 更新运动员信息成功后，更新表格信息
    updateTableAthlete (res) {
      const _athleteData = this.tableData[this.currentAthleteIndex];
      const _nationDict = this.dict.nation || [];
      const _nationData = _nationDict.find(item => item.code === res.national);
      _athleteData.idCardNumber = res.idCardNumber;
      _athleteData.name = res.name;
      _athleteData.imagePath = res.imagePath;
      _athleteData.national = _nationData ? _nationData.value : '';
    },
    // 切换模态框Loading状态
    changeModalLoading (val) {
      this.modalLoading = val;
    },
    // 获取运动员信息
    getAthleteInfo (athleteId) {
      this.dialogVisibleForPersonal = true;
      this.dialogVisibleForPersonalLoading = true;
      api_GET_EventsManagementRegisterId(athleteId)
        .then(
          res => {
            this.dialogVisibleForPersonalLoading = false;
            this.athleteInfo = res;
            CopyData(res, this.athleteVO);
          })
        .catch(
          error => {
            this.dialogVisibleForPersonalLoading = false;
            this.$message({ type: 'error', message: (error.error && error.error.message || '获取运动员信息失败') });
          }
        );
    },
    // 上传成功
    uploadSuccess (res) {
      console.log('uploadSuccess: ', res);
      res = res || [];
      const _upSuccessList = [];
      const _upFailList = [];
      res.forEach(item => {
        if (item.isSucceed) {
          _upSuccessList.push(item);
        } else {
          _upFailList.push(item);
        }
      });
      this.tableData = _upSuccessList;
      this.failTableData = _upFailList;
    },
    // 上传失败
    uploadFail (error) {
      this.$message({ type: 'error', message: '导入人员失败' });
      console.log('uploadFail error: ', error);
    },
    downloadTmp(url, fileName) {
      var x = new XMLHttpRequest();
      x.open('GET', url, true);
      x.responseType = 'blob';
      x.onload = function(e) {
        var url = window.URL.createObjectURL(x.response);
        var a = document.createElement('a');
        a.href = url;
        a.download = fileName + '.xlsx';
        a.click();
      };
      x.send();
    }
  }
};
</script>

<style lang="scss" scoped>
.mock_btn {
  display: inline-block;
  padding: 7px 15px;
  font-size: 12px;
  border-radius: 3px;
  line-height: 1;
  white-space: nowrap;
  cursor: pointer;
  background: #FFFFFF;
  text-align: center;
  box-sizing: border-box;
  outline: none;
  margin: 0;
  transition: 0.1s;
  font-weight: 400;
  border: 1px solid #DCDFE6;
}

.fail_text {
  display: inline-block;
  vertical-align: middle;
}

.import_info {
  font-size: 12px;
  line-height: 28px;
}
.fail_athlete_list {
  max-height: 200px;
  padding-right: 30px;
  overflow-y: auto;
  font-size: 12px;
}
.fail_athlete_item {
  padding-bottom: 2px;
  border-bottom: 1px solid #e8e8e8;
}
.fail_athlete_item:last-child {
  border-bottom: none;
}
.import_athlete_face {
  width: 30px;
  height: 42px;
  vertical-align: middle;
}
</style>
